package com.yfqy.admin.security.exception;

import cn.hutool.json.JSONUtil;
import com.yfqy.admin.constant.MyConstants;
import com.yfqy.admin.domain.vo.common.ResultVO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: 梁二东
 * @Date: 2025/5/3 12:55
 * @Description:认证成功(Authentication), 但无权访问时会执行这个方法，或者SpringSecurity框架捕捉到  AccessDeniedException时，会转出
 **/
public class CustomAuthorizationExceptionHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
        response.setContentType(MyConstants.CHARSET_UTF8);
        response.setStatus(HttpStatus.FORBIDDEN.value());
        PrintWriter writer = response.getWriter();
        writer.print(JSONUtil.toJsonStr(ResultVO.fail("${low.power:无权访问}")));
        writer.flush();
        writer.close();
    }
}
